package com.bruce.starts.demo.commonerror.controller;

import com.bruce.starts.demo.commonerror.dao.UserRepository;
import com.bruce.starts.demo.commonerror.dto.UserDto;
import com.bruce.starts.demo.commonerror.entity.UserEntity;
import com.bruce.starts.demo.commonerror.transaction.TransactionExecuteDemo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

/**
 * @author luotuan
 * @Description
 * @create 2021-05-11 15:03
 **/
@RestController
@RequestMapping("user")
public class UserController {
    @Autowired
    private UserRepository userRepository;
    @Autowired
    private TransactionExecuteDemo executeDemo;

    @RequestMapping("update")
    public UserEntity updateUser(@RequestBody UserDto user) {
        if (user == null || user.getId() == null) {
            throw new IllegalArgumentException("用户id不能为空");
        }
        UserEntity userEntity = userRepository.findById(user.getId()).orElseThrow(() -> new IllegalArgumentException("查询的用户不存在"));
        if (user.getName().isPresent()) {
            userEntity.setName(user.getName().orElse(""));
        }
        userEntity.setNickName("guest" + userEntity.getName());
        if (user.getAge().isPresent()) {
            userEntity.setAge(user.getAge().orElseThrow(() -> new IllegalArgumentException("用户的年龄不能为空")));
        }
        return userRepository.save(userEntity);
    }

    @RequestMapping("transaction")
    public String transaction() throws InterruptedException {
        executeDemo.serviceTest();
        return "成功";
    }
}
